#!/bin/bash

if [ -z $1 ]; then
	echo "Usage: ./deploy.sh xxx.app [/path/to/macdeployqt]"
	exit 1;
fi;


EXENAME=`basename "$1" | cut -d '.' -f 1`
BINPATH=`dirname "$0"`
BUILD_DIR=`dirname $1`

if [ ! -d $1/Contents/Frameworks ]; then
	mkdir $1/Contents/Frameworks
fi

echo "Copying Icon..."
mkdir -p $1/Contents/Resources/
cp res/bluecherry.icns $1/Contents/Resources/
echo "Copying translations.."
mkdir -p $1/Contents/Resources/translations
cp $BUILD_DIR/*.qm $1/Contents/Resources/translations/

#echo "Copying Breakpad framework..."
#rm -r $1/Contents/Frameworks/Breakpad.framework
#cp -R breakpad-bin/mac/Breakpad.framework $1/Contents/Frameworks/

#echo "Copying mplayer..."
#cp mplayer-bin/mac/mplayer $1/Contents/MacOS/
cp -a ~/bc-dev/libmpv/lib/lib*.dylib $1/Contents/Frameworks/

echo "Copying libav..."
#LIBAV_PATH=/usr/lib/bluecherry/client
#cp -a $BUILD_DIR/ffmpeg/install${LIBAV_PATH}/lib*.dylib $1/Contents/Frameworks
LIBAV_PATH=$HOME/bc-dev/ffmpeg
cp -a $LIBAV_PATH/lib/lib*.dylib $1/Contents/Frameworks

echo "Replacing library paths..."
#$BINPATH/replacepath.py --old $HOME/dev/usr/lib/ --new @executable_path/../Frameworks/ --file $1/Contents/MacOS/$EXENAME
#$BINPATH/replacepath.py --old @executable_path/../Resources/lib/ --new @executable_path/../Frameworks/ --dir $1/Contents/Frameworks/
$BINPATH/replacepath.py --old ${LIBAV_PATH}/ --new @executable_path/../Frameworks/ --file $1/Contents/MacOS/$EXENAME
$BINPATH/replacepath.py --old ${LIBAV_PATH}/ --new @executable_path/../Frameworks/ --dir $1/Contents/Frameworks/

if [ ! -z $2 ]; then
	echo "Running macdeployqt..."
	$2 $1
fi

echo "Removing unused plugins..."
rm $1/Contents/PlugIns/imageformats/lib{qico,qmng,qsvg,qtiff}.dylib
rm -r $1/Contents/PlugIns/{accessible,bearer,codecs,graphicssystems,iconengines,phonon_backend,qmltooling,script,sqldrivers}

echo "Running lipo..."
for I in $1/Contents/Frameworks/*.dylib; do
	FILE=$I;
        if [ `file $FILE | grep -c 'for architecture'` == "0" ]; then
		echo "    Skipping $FILE (already thin)"
        else
		lipo -thin i386 -output $FILE $FILE
	fi
done

for I in `find $1/Contents/Frameworks/*.framework/Versions -type f -maxdepth 2`; do
    if [ `file $I | grep -c 'for architecture'` == "0" ]; then
        echo "    Skipping $I (already thin)"
    else
        lipo -thin i386 -output $I $I
    fi
done
